<template>
    <view>
        <view>
            <j-cell-group :title="$t('General.family.systemDefault')">
                <template v-for="(item, index) in roomList">
                    <j-cell :key="item.id" :title="item.roomName" :tips="item.deviceCount + $t('General.family.xDevices')" v-if="item.isDefault" :more="false"></j-cell>
                </template>
            </j-cell-group>

            <j-cell-group :title="$t('General.family.createdHome')">
				<!--成员不应该能创建房间-->
                <!-- <view slot="action" v-if="group.isCreator"> -->
				<view slot="action">
					<uni-icons custom-prefix="iconfont" type="icon-jiahao" size="20" @tap="onBindtapAddRoom(group)"></uni-icons>
                </view>

                <template v-for="(item, index) in roomList">
					<!--成员不应该能编辑/删除房间-->
					<!-- <j-cell-slider
						:key="item.id"
					    :title="item.roomName"
					    :tips="item.deviceCount + '个设备'"
					    v-if="!item.isDefault"
					    :is-touch="group.isCreator"
					    :is-tap="group.isCreator"
					    :more="group.isCreator"
					    @jftap="onBindtapUpdate(item)"
					    @jfdelete="onBinddeleteRoom(item)"
					></j-cell-slider> -->
					
                    <j-cell-slider
						:key="item.id"
                        :title="item.roomName"
                        :tips="item.deviceCount + $t('General.family.xDevices')"
                        v-if="!item.isDefault"
                        :more="group.isCreator"
                        @jftap="onBindtapUpdate(item)"
                        @jfdelete="onBinddeleteRoom(item)"
                    ></j-cell-slider>
                </template>
            </j-cell-group>
        </view>
		
<!--		<uni-popup ref="popup" class="popupName" :isMaskClick="false" @change="change" @maskClick="maskClick">-->
<!--			<form @submit="submit">-->
<!--				<view class="form">-->
<!--					<view class="form-item">-->
<!--						<input :focus="focus" placeholder="请输入房间名称" name="roomName" v-model="roomName" class="form-control" style="background: #f6f6f6" @confirm="submit" />-->
<!--					</view>-->
<!--					<view class="form-item">-->
<!--						<button type="primary" form-type="submit">确认</button>-->
<!--					</view>-->
<!--				</view>-->
<!--			</form>-->
<!--		</uni-popup>-->
        <j-modal :value="value" @ok="submit" @cancel="() => {value = false}" @mask="maskClick">
            <template slot="content">
                <form>
                    <input :focus="focus" :placeholder="$t('General.family.roomPla')" name="groupName" v-model="roomName"
                           class="form-control" style="background: #f6f6f6;text-align: left" />
                </form>
            </template>
        </j-modal>
		<j-modal :value="delPopupVisible" :showCancel="true" :title="$t('General.family.tip')" @cancel="delPopupVisible = false" @ok="confirmDelClick">
			<view slot="content">
				{{$t('General.family.confirmDelete')}}
			</view>
		</j-modal>
    </view>
</template>

<script>
let that = null
const {debounce} = require('@/utils/util.js')
export default {
    data() {
        return {
            groupId: '',
            group: {
                isCreator: ''
            },
            roomList: [],
            focus: false,
            roomName: '',
            roomId: '' ,// 用于更新房间
			delPopupVisible:false,
			id:'',
            value: false,
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        console.log('=== room-list:onLoad:', options.groupId);
        this.groupId = options.groupId
		that = this
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('=== room-list:management:onReady:');
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('=== room-list:management:onShow:');
        uni.setNavigationBarTitle({
            title: this.$t('General.family.roomManagement')
        })
        let groupList = uni.getStorageSync('groupList'); //getApp().globalData.groupList

        for (let i = 0; i < groupList.length; i++) {
            const item = groupList[i];

            if (item.id === this.groupId) {
                this.group = item
            }
        }

        this.getRoomListByPage();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('--- room-list:management:onHide:');
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        console.log('--- room-list:management:onUnload:');
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 分页查询房间列表
        getRoomListByPage(status = 0) {
            const data = {
                userGroupId: this.groupId,
                page: 1,
                limit: 999
            };
            getApp().globalData.api.getRoomListByPage(data, (result) => {
                console.log('查询房间列表:', result);
                this.roomList = result.data
                if(status) {
                    this.$nextTick(() => {
                        uni.showToast({
                            title: this.$t('General.family.successDeleteRoom'),
                            duration:2000,
                        });
                    })
                }
            });
        },

        // 新增房间
        onBindtapAddRoom(ev) {
			// this.$refs.popup.open()
            this.value = true
            this.roomName = ''
            this.roomId = ''
            setTimeout(() => {
                this.focus = true
            }, 350);
        },

        // 修改房间名称
        onBindtapUpdate(ev) {
            console.log('修改房间名称:', ev);
            const room = ev;
			// this.$refs.popup.open()
            this.value = true
            this.roomName = room.roomName
            this.roomId = room.id
            setTimeout(() => {
                    this.focus = true
            }, 350);
        },

        // 表单提交
        submit(ev) {
            if (this.roomName.replace(/\s/g, '') === '') {
                uni.showToast({
                    title: this.$t('General.family.roomPla'),
                    icon: 'none'
                });
                return;
            }
            if (this.roomName.length < 2 || this.roomName.length > 50) {
                uni.showToast({
                  title: this.$t('General.family.tipRoomLength'),
                  icon: 'none'
                });
                return;
              }

            if (this.roomId === '') {
                let data = {
                    userGroupId: this.groupId,
                    roomName: this.roomName
                };
                uni.showLoading({
                    mask: true
                })
                getApp().globalData.api.addRoom(data, (result) => {
					// this.$refs.popup.close()
                    this.value = false
                    setTimeout(() => {
                        uni.showToast({
                            title: this.$t('General.family.createSuccess')
                        })
                    })
                    this.focus = false
                    this.roomName = ''
                    this.roomId = ''
					this.getRoomListByPage();
                });
            } else {
                let data = {
                    id: this.roomId,
                    roomName: this.roomName
                };
                getApp().globalData.api.updateRoom(data, (result) => {
					// this.$refs.popup.close()
                    this.value = false
                    this.focus = false
                    this.roomName = ''
                    this.roomId = ''
					this.getRoomListByPage();
                });
            }
        },

        // 删除房间
        onBinddeleteRoom(ev) {
			this.delPopupVisible = true
			this.id = ev.id
        },
		confirmDelClick:debounce(()=>{
			that.confirmDelClick2()
		}),
		//确认删除
		confirmDelClick2(){
			uni.showLoading({
				title:this.$t('General.family.deleting'),
                mask: true
            })
			const data = {
			    id: this.id
			};
			getApp().globalData.api.delRoom(data, (result) => {
				this.delPopupVisible = false
			    // uni.showToast({
			    //     title: '删除房间成功！',
				// 	duration:2000,
			    //     success: (res) => {
				// 		setTimeout(()=>{
				// 			this.getRoomListByPage();
				// 		})
			    //     }
			    // });
                setTimeout(()=>{
                    this.getRoomListByPage(1);
                })
			});
		},
		change(ev){
			console.log('change:',ev);
		},
		maskClick(ev){
			console.log('maskClick',ev);
			this.focus = false
            // this.$refs.popup.close()
            this.value = false
            this.roomName = ''
		},
    }
};
</script>
<style lang="scss">
	.popupName {
		/deep/ .uni-popup__wrapper {
			top: -100rpx;
		}
	}
	.form {
		background: white;
		padding: 60rpx;
		border-radius: 10rpx;
	}
	
	.form .form-item {
		margin-top: 20rpx;
	}
	
	.form .form-title {
		text-align: center;
		margin-bottom: 40rpx;
		font-weight: bold;
	}
	
	.form .form-item .form-control {
		background: #efefef;
	}
</style>
